package top.laoshuzi.android.tts.service;

import android.content.Context;
import android.os.*;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import top.laoshuzi.android.tts.ITtsService;

/**
 * Created by Mouse on 2017/6/1.
 */

public class TtsServiceImpl extends ITtsService.Stub {


    private static final int TTS_SPEAK_WHAT = 0x20000003;

    private Context context;

    private Handler ttsHandler;
    private HandlerThread ttsThread;

    private TextToSpeech textToSpeech;
    private TextToSpeech.OnInitListener onInitListener;

    private boolean isOpen = false;

    public TtsServiceImpl(Context context) {
        this.context = context;
        onInitListener = new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

            }
        };

    }

    @Override
    public void open() {
        if (isOpen) {
            Log.i("TtsService", "tts 已打开");
            return;
        }

        Log.i("TtsService", "tts open!");
        textToSpeech = new TextToSpeech(context, onInitListener);

        ttsThread = new HandlerThread("TTS_THREAD");
        ttsThread.start();
        ttsHandler = new TtsHandler(ttsThread.getLooper());

        isOpen = true;
    }

    @android.support.annotation.RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void shutdown() {
        if (!isOpen) {
            Log.i("TtsService", "tts 已关闭");
            return;
        }

        Log.i("TtsService", "tts shutdown!");
        if (ttsHandler != null) {
            ttsHandler.removeMessages(TTS_SPEAK_WHAT);
            ttsHandler = null;
            ttsThread.quitSafely();
        }

        textToSpeech.stop();
        textToSpeech.shutdown();

        isOpen = false;
    }

    @Override
    public void speak(String text, int mode) {

        if (ttsHandler == null) {
            Log.w("TtsService", "tts service is shutdown");
            return;
        }

        Message msg = ttsHandler.obtainMessage();
        msg.arg1 = mode;
        msg.what = TTS_SPEAK_WHAT;
        msg.obj = new String(text);
        ttsHandler.sendMessage(msg);
    }


    private void speak_0(String text, int mode) {
        Log.d("TtsService", "[mode:" + mode + " text:" + text + "]");
        textToSpeech.speak(text, mode, null);
    }

    public boolean isOpen() {
        return isOpen;
    }

    private class TtsHandler extends Handler {

        public TtsHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {

            if (msg.what == TTS_SPEAK_WHAT) {
                speak_0(String.valueOf(msg.obj), msg.arg1);
            }
            super.handleMessage(msg);
        }
    }
}
